<template>
  <div v-show="show" :class="[{'t-notice': true}]">
    <div class="t-notice__content" ref="content"></div>
    <div v-if="type === 'tomato'">
      <t-rate usePic="true" :level="tomatoLevel" @select="setLevel"></t-rate>
    </div>
    <span v-if="closable">
      <div class="t-notice__close-x">
        <a tabIndex="0" @click="handleClose"><i class="iconfont icon-guanbi"></i></a>
      </div>
    </span>
  </div>
</template>

<script>
  import TRate from '@/components/rate';
  
  export default {
    components: {
      TRate,
    },
    props: {
      duration: {
        type: [Number],
        default: 4.5,
      },
      content: String,
      closable: Boolean,
      onClose: Function,
      type: String,
    },
    data() {
      return {
        show: true,
        tomatoLevel: 1,
      };
    },
    watch: {
      content() {
        this.renderContent();
      },
    },
    beforeMount() {
      this.clearCloseTimer();
      if (this.duration) {
        this.closeTimer = setTimeout(() => {
          this.close();
        }, this.duration * 1000);
      }
    },
    mounted() {
      this.renderContent();
    },
    beforeDestory() {
      this.clearCloseTimer();
    },
    methods: {
      setLevel(level) {
        this.tomatoLevel = level;
        this.write(this.tomatoLevel);
        window.setTimeout(() => {
          this.close();
        }, 1000);
      },
      renderContent() {
        const node = this.$refs.content;
        node.innerHTML = this.content;
      },
      handleClose() {
        this.close();
      },
      clearCloseTimer() {
        if (this.closeTimer) {
          window.clearTimeout(this.closeTimer);
          this.closeTimer = null;
        }
      },
      close() {
        this.show = false;
        this.clearCloseTimer();
        if (this.onClose) {
          this.onClose();
        }
      },
      write(level) {
        const token = this.$stateHub.csrf;
        const target = 'api/rate';
        this.$http.request({
          url: target,
          method: 'post',
          data: {
            token,
            level,
          },
          transformRequest: [(data) => {
            const encodeToken = encodeURIComponent(data.token);
            const encodeLevel = encodeURIComponent(data.level);
            return `_csrf=${encodeToken}&level=${encodeLevel}`;
          }],
        }).then((response) => {
          this.$stateHub.csrf = response.data.csrf;
          this.$refs.content.innerHTML = '<p class="t-notice--tomato__message">感谢您的评价！</p>';
        }).catch((error) => {
          this.$stateHub.csrf = error.response.data.csrf;
        });
      },
    },
  };
</script>